package com.content.scaffold.model.enums;

/**
 * @author xiaojl
 */
public enum SensitiveType {
    // 基础类型
    PHONE("^((?:\\d{3}))\\d{4}((?:\\d{4}))$", "$1****$2"),
    ID_CARD("^(\\d{4})\\d{10}(\\w{4})$", "$1**********$2"),
    BANK_CARD("^(\\d{4})\\d{8}(\\d{4})$", "$1****$2"),
    EMAIL("^((?:\\w?))(\\w+)((?:\\w))(@\\w+\\.[a-z]+(?:\\.[a-z]+)?)$", "$1****$3$4"),
    NAME("^([\\u4e00-\\u9fa5]{1})(.*)$", "$1*"),

    // 扩展类型
    PLATE_NUMBER("^([\\u4e00-\\u9fa5]{1})([A-Z]{1})([A-Z0-9]{4})$", "$1$2****"),
    // 注意：原逻辑可能有问题，保留原始语义
    ADDRESS("^((?:.{5}))(.*)(?:$)", "$1****$3"),
    DEFAULT("^((?:.{5}))(.*)(?:$)", "$1****$3");

    private final String regex;
    private final String replacement;

    SensitiveType(String regex, String replacement) {
        this.regex = regex;
        this.replacement = replacement;
    }

    public String desensitize(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        try {
            return input.replaceAll(regex, replacement);
        } catch (Exception e) {
            // 防止正则表达式错误导致崩溃
            return input;
        }
    }

    /**
     * 批量脱敏工具方法
     */
    public static String process(String input, SensitiveType type) {
        return type.desensitize(input);
    }

    /**
     * 自动识别类型脱敏
      */

    public static String autoDesensitize(String input) {
        if (input == null) {
            return null;
        }

        for (SensitiveType type : values()) {
            if (input.matches(type.regex)) {
                return type.desensitize(input);
            }
        }

        return input;
    }
}
